package com.example.secondhandspringboot.handler;

import com.example.secondhandspringboot.exception.BaseException;
import com.example.secondhandspringboot.results.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //捕获请求参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result exceptionHandler(MethodArgumentNotValidException ex){
        log.info("已捕获请求参数校验异常");
        FieldError fieldError = ex.getBindingResult().getFieldError();
        return Result.error(fieldError.getDefaultMessage());
    }

    @ExceptionHandler(BaseException.class)
    public Result exceptionHandler(BaseException ex){
        log.info("已捕获BaseException异常");
        return Result.error(ex.getMessage());
    }

}
